<?php

class tuentiLoader{
	
	private $usuario;
	private $pass;
	private $ch;
	function tuentiLoader($usuario,$pass)
	{
		$this->usuario = $usuario;
		$this->pass = $pass;
	}
	
	public function cerrarSesion()
	{
		curl_close($this->ch);
	}
	public function iniciarSesion()
	{
		$url="http://m.tuenti.com/?m=login&func=process_login";
				$this->ch = curl_init();
				curl_setopt($this->ch, CURLOPT_URL,$url);
				curl_setopt ($this->ch, CURLOPT_COOKIESESSION, true);
				curl_setopt($this->ch, CURLOPT_COOKIEFILE, 'cookiefile.txt');
				curl_setopt($this->ch, CURLOPT_COOKIEJAR, 'cookiefile.txt'); 
				curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);	 
				curl_setopt ($this->ch, CURLOPT_POST, 1);
				curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
				curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); 
				curl_setopt ($this->ch, CURLOPT_POSTFIELDS, "tuentiemail=".$this->usuario."&password=".$this->pass);
				$res = curl_exec ($this->ch);
				if(strpos($res,"system_error"))
					return false;
				else
					return true;

	}
	
	public function listar_amigos(){ 
   
		$listaAmigos = array();
		$pagina = 0;
		
		$continuar = true;
		
	    while($continuar)
	    {
			curl_setopt($this->ch, CURLOPT_URL,"http://m.tuenti.com/?m=friends&page=".$pagina);
			$resultado = curl_exec ($this->ch);
			$doc = new DOMDocument();
		    @$doc->loadHTML($resultado);
		    $totalAmigos = $doc->getElementsByTagName("small");
		    preg_match("/([0-9]*) - ([0-9]*) de ([0-9]*) amigos/", $totalAmigos->item(0)->nodeValue, $datos);
		    $totales = $datos[3];
		    $actuales = $datos[2];
		    for($i=2; $i<=10; $i+=2)
		    {
		    	$item=$totalAmigos->item($i)->getElementsByTagName("a")->item(0);
		    	if(is_object($item)){
		    		$amigo['identificador'] = $item->getAttribute("href");
			    	$amigo['nombre']= $item->nodeValue;
			    	
			    	$amigo['identificador'] = split("user_id=",$amigo['identificador']);
			    	$amigo['identificador'] = $amigo['identificador'][1];
			    	
			    	$listaAmigos[] = $amigo;
		    	}
		    }
		    $pagina++;
		    if($actuales==$totales)
		    	$continuar = false;
	    }
	    return $listaAmigos;
	}
	
	public function enviarPrivado($uuid,$mensaje)
	{
		$url="http://m.tuenti.com/?m=messaging&func=compose_message&user_id=".$uuid;
		curl_setopt($this->ch, CURLOPT_URL,$url);
		$resultado = curl_exec ($this->ch);
		$doc = new DOMDocument();
		@$doc->loadHTML($resultado);
		$form = $doc->getElementsByTagName("form");
		
		$url = "http://m.tuenti.com/".$form->item(0)->getAttribute("action");
		curl_setopt($this->ch, CURLOPT_URL,$url);
		curl_setopt ($this->ch, CURLOPT_POSTFIELDS, "text=".$mensaje);
		curl_exec ($this->ch);
		//?m=messaging&func=process_send_message&user_id=60751210&csfr=7f875427
	}
		
}